package com.example.notice.news

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.base.entity.NewsEntityItem
import com.example.notice.R
import com.example.notice.databinding.ItemNewsBinding

class NewsPageAdapter :PagingDataAdapter<NewsEntityItem,NewsPageAdapter.NewsViewHolder>(diff){
    private var monItemClickLister:onItemClickLister? = null


    fun setOnItemClickLister(lister: onItemClickLister){
        this.monItemClickLister = lister
    }
    companion object{
        val diff = object :DiffUtil.ItemCallback<NewsEntityItem>(){
            override fun areItemsTheSame(
                oldItem: NewsEntityItem,
                newItem: NewsEntityItem
            ): Boolean {
                return oldItem.id==newItem.id
            }

            override fun areContentsTheSame(
                oldItem: NewsEntityItem,
                newItem: NewsEntityItem
            ): Boolean {
                return oldItem==newItem
            }
        }
    }

    class NewsViewHolder(itemView:View):ViewHolder(itemView){
        val binding = DataBindingUtil.bind<ItemNewsBinding>(itemView)
    }

    override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
        val item = getItem(position)!!
        holder.binding?.newsTitle?.text = item.title
        holder.binding?.newsContent?.text = item.content
        holder.binding?.newsTime?.text = item.publishDate
        holder.binding?.newsCancel?.apply {
            if(item.published){
                this.isVisible = true
            }else{
                this.isVisible = false
            }
        }
        holder.itemView.setOnClickListener {
            monItemClickLister?.onItemClick(position,item)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
        val inflate = LayoutInflater.from(parent.context).inflate(R.layout.item_news, null)
        return NewsViewHolder(inflate)
    }
}

/**
 * 定义接口
 */
interface onItemClickLister{
    fun onItemClick(position: Int,item:NewsEntityItem)
}